const chalk = require('chalk')
const fs = require('fs')
const Mock = require('mockjs')
const express = require('express')
const cors = require('cors')
const { join, resolve, extname, sep } = require('path')
console.clear()

/** 导入依赖补丁 */
require(`${resolve('src')}/utils/legacy`)

/** 全局注册 */
globalThis.src = resolve('src')

/** express 应用配置 */

const root = join(__dirname, 'module')
const blacklist = ['index.js']
const suffix = ['.js']
const PORT = 5550

const app = express()
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.listen(PORT, console.log.call(null, chalk.bgGreen(' Mock Server is running at：')))

/** 递归遍历文件夹 */
const loopFilesByDirectory = async dir => {
  fs.readdirSync(dir).forEach(file => {
    const joinPath = join(dir, file)

    if (fs.isDir(joinPath)) loopFilesByDirectory(joinPath)
    else {
      if (blacklist.includes(file) || !suffix.includes(extname(joinPath))) return

      let mocks = require(joinPath)
      if (!Array.isArray(mocks)) mocks = [mocks]

      mocks.forEach(item => {
        const directory = dir.replace(root, '')
        const latest = item.url ? item.url : file.replace(/\.\w{0,}/, '')
        const composit = join(directory, latest)
        const url = composit.startsWith(sep) ? composit : `${sep}${composit}`
        app[item.type && item.type.toLowerCase()](url.replace(/\\\\?/g, '/'), (req, res) => res.json(Mock.mock(item.response instanceof Function ? item.response(req, res) : item.response)))
      })
    }
  })
}

loopFilesByDirectory(root)

/** 打印路由信息 */
app._router.stack.forEach(item => {
  if (!item.route) return
  const { methods, path } = item.route
  Object.keys(methods).forEach(method => console.log(`${chalk.bgRed(' ' + method.toUpperCase() + ' ')}`, chalk.green(`http://localhost:${PORT}${path}`)))
})
